package com.gzrhhscd.filter;

import com.alibaba.fastjson.JSONObject;
import com.gzrhhscd.Pojo.Result;
import com.gzrhhscd.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.get url
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String url=request.getRequestURI();
        log.info("请求的URL：{}",url);
        //2.if login let go
        if (url.contains("login")){
            log.info("登录操作，放行……");
            filterChain.doFilter(request,response);
            return;
        }
        //3.get the token
        String jwt=request.getHeader("token");
        //4.if jwt is null or doesn't exit , return NOT LOGIN
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头taken为空，返回未登录信息");
            Result error=Result.error("NOT_LOGIN");
            String notLogin= JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }
        //5.parse jwt  if illegal return Not login
        try {
            JwtUtils.parseJwt(jwt);
        } catch (Exception e) {

            log.info("解析令牌失败，返回未登录错误信息");
            Result error=Result.error("NOT_LOGIN");
            String notLogin= JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }
        //6.解析成功，放行
        log.info("令牌合法，放行");
        filterChain.doFilter(request,response);
    }
}
